// services/activation_service.dart
import 'package:shared_preferences/shared_preferences.dart';
import 'database_service.dart';
import 'dart:io';
import 'package:flutter/material.dart';

// 添加 ActivationResult 类定义
class ActivationResult {
  final bool success;
  final String? message;
  final DateTime? expireTime;
  final String? activationCode;

  ActivationResult({
    required this.success,
    this.message,
    this.expireTime,
    this.activationCode,
  });
}

class ActivationService {
  static final ActivationService _instance = ActivationService._internal();
  factory ActivationService() => _instance;
  ActivationService._internal();

  final DatabaseService _databaseService = DatabaseService();
  
  bool _activated = false;
  String _activationCode = '';
  DateTime? _expireTime;

  bool get isActivated => _activated;
  String get activationCode => _activationCode;
  DateTime? get expireTime => _expireTime;

  // 检查激活状态
  Future<ActivationResult> checkActivation(String code) async {
    try {
      // 验证激活码格式
      if (code.isEmpty) {
        return ActivationResult(
          success: false,
          message: '激活码不能为空',
        );
      }

      // 数据库验证
      final result = await _databaseService.checkActivationCode(code);
      
      if (result.success) {
        _activated = true;
        _activationCode = result.activationCode!;
        _expireTime = result.expireTime;
        
        // 保存到本地存储
        await _saveActivationData(code, result.expireTime!);
        
        return ActivationResult(
          success: true,
          expireTime: result.expireTime,
        );
      } else {
        return ActivationResult(
          success: false,
          message: result.message,
        );
      }
    } catch (e) {
      print('激活验证错误: $e');
      return ActivationResult(
        success: false,
        message: '验证过程中发生错误: $e',
      );
    }
  }

  // 从本地存储加载激活状态
  Future<bool> loadActivationFromStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final savedCode = prefs.getString('activation_code');
      final savedExpire = prefs.getString('activation_expire');
      
      if (savedCode != null && savedExpire != null) {
        final expireTime = DateTime.parse(savedExpire);
        final currentTime = DateTime.now();
        
        if (expireTime.isAfter(currentTime)) {
          _activated = true;
          _activationCode = savedCode;
          _expireTime = expireTime;
          
          // 验证激活码是否仍然有效（可选）
          final result = await _databaseService.checkActivationCode(savedCode);
          if (result.success) {
            return true;
          } else {
            // 本地存储的激活码在服务器端已失效
            await clearActivationData();
            return false;
          }
        } else {
          // 激活码已过期
          await clearActivationData();
          return false;
        }
      }
      return false;
    } catch (e) {
      print('加载激活数据错误: $e');
      return false;
    }
  }

  // 保存激活数据到本地
  Future<void> _saveActivationData(String code, DateTime expireTime) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('activation_code', code);
      await prefs.setString('activation_expire', expireTime.toIso8601String());
    } catch (e) {
      print('保存激活数据错误: $e');
    }
  }

  // 清除激活数据
  Future<void> clearActivationData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('activation_code');
      await prefs.remove('activation_expire');
      
      _activated = false;
      _activationCode = '';
      _expireTime = null;
    } catch (e) {
      print('清除激活数据错误: $e');
    }
  }

  // 检查是否过期
  bool get isExpired {
    if (_expireTime == null) return true;
    return DateTime.now().isAfter(_expireTime!);
  }

  // 获取剩余天数
  int get daysLeft {
    if (_expireTime == null) return 0;
    final now = DateTime.now();
    final difference = _expireTime!.difference(now);
    return difference.inDays;
  }

  // 获取激活状态文本
  String get statusText {
    if (!_activated) return '未激活';
    
    if (isExpired) {
      return '激活已过期';
    }
    
    final expireStr = _expireTime!.toString().split(' ')[0];
    final days = daysLeft;
    
    if (days > 7) {
      return '已激活 (到期: $expireStr)';
    } else if (days > 0) {
      return '已激活 (剩余: ${days}天)';
    } else {
      final hoursLeft = _expireTime!.difference(DateTime.now()).inHours;
      return '已激活 (剩余: ${hoursLeft}小时)';
    }
  }

  // 断开数据库连接
  Future<void> dispose() async {
    await _databaseService.dispose();
  }

  // 获取激活状态颜色
  Color get statusColor {
    if (!_activated) return Colors.red;
    if (isExpired) return Colors.red;
    
    final days = daysLeft;
    if (days > 7) return Colors.green;
    if (days > 3) return Colors.orange;
    return Colors.red;
  }

  // 获取详细的激活状态文本
  String get detailedStatusText {
    if (!_activated) return '未激活';
    
    if (isExpired) {
      return '激活已过期';
    }
    
    final expireStr = _expireTime!.toString().split(' ')[0];
    final days = daysLeft;
    final hoursLeft = _expireTime!.difference(DateTime.now()).inHours;
    
    if (days > 7) {
      return '已激活 • 到期: $expireStr • 剩余: ${days}天';
    } else if (days > 0) {
      return '已激活 • 到期: $expireStr • 剩余: ${days}天';
    } else {
      return '已激活 • 到期: $expireStr • 剩余: ${hoursLeft}小时';
    }
  }

  // 获取简化的状态文本（用于状态栏）
  String get shortStatusText {
    if (!_activated) return '未激活';
    
    if (isExpired) {
      return '已过期';
    }
    
    final days = daysLeft;
    if (days > 7) return '已激活';
    if (days > 0) return '剩余${days}天';
    final hoursLeft = _expireTime!.difference(DateTime.now()).inHours;
    return '剩余${hoursLeft}小时';
  }

  // 检查是否需要显示警告（剩余时间少于7天）
  bool get shouldShowWarning {
    if (!_activated || isExpired) return false;
    return daysLeft <= 7;
  }

  // 获取剩余时间的百分比（用于进度显示）
  double get remainingPercentage {
    if (!_activated || _expireTime == null) return 0.0;
    
    final totalDuration = _expireTime!.difference(DateTime.now().subtract(Duration(days: 30))).inDays.toDouble();
    final remainingDuration = _expireTime!.difference(DateTime.now()).inDays.toDouble();
    
    if (totalDuration <= 0) return 0.0;
    return (remainingDuration / totalDuration).clamp(0.0, 1.0);
  }

}